package com.dl.study.config.jwt;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.dl.study.config.propertites.JwtProperties;
import com.dl.study.config.redis.RedisConstant;
import com.dl.study.handler.ClueBusinessException;
import com.dl.study.util.Base64Util;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.UnsupportedEncodingException;
import java.util.Date;

/**
 * @Author: user
 * @Date: 2021/10/22 14:36
 * @Description:
 */
@Component
@Slf4j
public class JwtUtil {
    /**
     * 过期时间改为从配置文件获取
     */
    private static String accessTokenExpireTime;
    /**
     * JWT认证加密私钥(Base64加密)
     */
    private static String encryptJWTKey;

    @Autowired
    private JwtProperties jwtProperties;


    @Autowired
    private static JwtUtil jwtUtil;

    @PostConstruct
    public void init() {
        jwtUtil = this;
        jwtUtil.jwtProperties = this.jwtProperties;
    }


    @Value("${token.accessTokenExpireTime}")
    public void setAccessTokenExpireTime(String accessTokenExpireTime) {
        JwtUtil.accessTokenExpireTime = accessTokenExpireTime;
    }

    @Value("${token.encryptJWTKey}")
    public void setEncryptJWTKey(String encryptJWTKey) {
        JwtUtil.encryptJWTKey = encryptJWTKey;
    }


    /**
     * 校验token是否正确
     *
     * @param token Token
     * @return boolean 是否正确
     * @author Wang926454
     * @date 2018/8/31 9:05
     */
    public static boolean verify(String token) {
        try {
            // 帐号加JWT私钥解密\//Base64Util.encodeThrowsException(encryptJWTKey)
            String secretKey = jwtUtil.jwtProperties.secretKey;
            String secret = getClaim(token, RedisConstant.ACCOUNT) + secretKey;
            Algorithm algorithm = Algorithm.HMAC256(secret);
            JWTVerifier verifier = JWT.require(algorithm).build();
            verifier.verify(token);
            return true;
        }
//        catch (UnsupportedEncodingException e) {
//            log.error("JWTToken认证解密出现UnsupportedEncodingException异常:" + e.getMessage());
//            e.printStackTrace();
//        }
        catch (AuthenticationException e) {
            log.error("JWTToken认证已过期:" + e.getMessage());
            e.printStackTrace();
        }
        return false;

    }

    /**
     * 获得Token中的信息无需secret解密也能获得
     *
     * @param token
     * @param claim
     * @return java.lang.String
     * @author Wang926454
     * @date 2018/9/7 16:54
     */
    public static String getClaim(String token, String claim) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            // 只能输出String类型，如果是其他类型返回null
            return jwt.getClaim(claim).asString();
        } catch (JWTDecodeException e) {
            log.error("解密Token中的公共信息出现JWTDecodeException异常:" + e.getMessage());
            throw new ClueBusinessException("解密Token中的公共信息出现JWTDecodeException异常:" + e.getMessage());
        }
    }

    /**
     * 生成签名,5min后过期
     *
     * @param account
     * @param currentTimeMillis
     * @return
     */
    public static String sign(String account, String currentTimeMillis) {

        try {
            // 帐号加JWT私钥加密
            //  Base64Util.encodeThrowsException(encryptJWTKey);
            String secretKey = jwtUtil.jwtProperties.secretKey;
            String secret = account + secretKey;
            // 此处过期时间是以毫秒为单位，所以乘以1000
            Date date = new Date(System.currentTimeMillis() + Long.parseLong(accessTokenExpireTime) * 60 * 1000);
            Algorithm algorithm = Algorithm.HMAC256(secret);
            // 附带account帐号信息
            return JWT.create()
                    .withClaim(RedisConstant.ACCOUNT, account)
                    .withClaim(RedisConstant.CURRENT_TIME_MILLIS, currentTimeMillis)
                    .withExpiresAt(date)
                    .sign(algorithm);
        }
//        catch (UnsupportedEncodingException e) {
//            log.error("JWTToken加密出现UnsupportedEncodingException异常:" + e.getMessage());
//            e.printStackTrace();
//        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {
        try {
            String sss = Base64Util.decodeThrowsException("U0JBUElOENhspJrzkyNjQ1NA");
            log.info(sss);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

}
